<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no"><title>54-Canvas | 小黑博客</title><meta name="keywords" content="JavaScript,JavaScript高级程序设计第四版"><meta name="author" content="BluesYoung-web"><meta name="copyright" content="BluesYoung-web"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="画布类型 2d webgl  使用步骤 获取 element 获取上下文对象 ctx &#x3D; element.getContext(&#39;2d&#39; || &#39;webgl&#39;) 绘制 导出图片 element.toDataURL(&#39;MIME&#x2F;TYPE&#39;)  2d上下文 可绘制简单的2d图形，比如矩形、弧线和路径 ctx.save() 保存现场 ctx.restore">
<meta property="og:type" content="article">
<meta property="og:title" content="54-Canvas">
<meta property="og:url" content="https://bluesyoung-web.gitee.io/blog/2021-01-25-54-Canvas.html">
<meta property="og:site_name" content="小黑博客">
<meta property="og:description" content="画布类型 2d webgl  使用步骤 获取 element 获取上下文对象 ctx &#x3D; element.getContext(&#39;2d&#39; || &#39;webgl&#39;) 绘制 导出图片 element.toDataURL(&#39;MIME&#x2F;TYPE&#39;)  2d上下文 可绘制简单的2d图形，比如矩形、弧线和路径 ctx.save() 保存现场 ctx.restore">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://bluesyoung-web.gitee.io/blog/img/hbs.png">
<meta property="article:published_time" content="2021-01-25T01:46:23.000Z">
<meta property="article:modified_time" content="2021-08-29T11:36:10.269Z">
<meta property="article:author" content="BluesYoung-web">
<meta property="article:tag" content="JavaScript">
<meta property="article:tag" content="JavaScript高级程序设计第四版">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://bluesyoung-web.gitee.io/blog/img/hbs.png"><link rel="shortcut icon" href="/blog/img/favicon.png"><link rel="canonical" href="https://bluesyoung-web.gitee.io/blog/2021-01-25-54-Canvas"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="stylesheet" href="/blog/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/node-snackbar/dist/snackbar.min.css" media="print" onload="this.media='all'"><script>const GLOBAL_CONFIG = { 
  root: '/blog/',
  algolia: undefined,
  localSearch: {"path":"search.xml","languages":{"hits_empty":"找不到您查询的内容：${query}"}},
  translate: undefined,
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":false},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '天',
  date_suffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: {"limitCount":50,"languages":{"author":"作者: BluesYoung-web","link":"链接: ","source":"来源: 小黑博客","info":"著作权归作者所有。商业转载请联系作者获得授权，非商业转载请注明出处。"}},
  lightbox: 'fancybox',
  Snackbar: {"chs_to_cht":"你已切换为繁体","cht_to_chs":"你已切换为简体","day_to_night":"你已切换为深色模式","night_to_day":"你已切换为浅色模式","bgLight":"#49b1f5","bgDark":"#121212","position":"top-right"},
  source: {
    jQuery: 'https://cdn.jsdelivr.net/npm/jquery@latest/dist/jquery.min.js',
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/justifiedGallery/dist/js/jquery.justifiedGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/justifiedGallery/dist/css/justifiedGallery.min.css'
    },
    fancybox: {
      js: 'https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox.umd.js',
      css: 'https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox.css'
    }
  },
  isPhotoFigcaption: false,
  islazyload: false,
  isanchor: true
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: '54-Canvas',
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: false,
  postUpdate: '2021-08-29 19:36:10'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          if (t === 'dark') activateDarkMode()
          else if (t === 'light') activateLightMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
    const detectApple = () => {
      if (GLOBAL_CONFIG_SITE.isHome && /iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
    })(window)</script><link rel="stylesheet" href="/blog/css/background.css"> <link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/sviptzk/HexoStaticFile@latest/Hexo/css/custom.min.css"></link><meta name="generator" content="Hexo 5.4.0"></head><body><div id="loading-box"><div class="loading-left-bg"></div><div class="loading-right-bg"></div><div class="spinner-box"><div class="configure-border-1"><div class="configure-core"></div></div><div class="configure-border-2"><div class="configure-core"></div></div><div class="loading-word">加载中...</div></div></div><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src="/blog/img/lufei_siwangningshi.jpg" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="site-data is-center"><div class="data-item"><a href="/blog/archives/"><div class="headline">文章</div><div class="length-num">153</div></a></div><div class="data-item"><a href="/blog/tags/"><div class="headline">标签</div><div class="length-num">54</div></a></div><div class="data-item"><a href="/blog/categories/"><div class="headline">分类</div><div class="length-num">48</div></a></div></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/blog/about/"><i class="fa-fw fas fa-heart"></i><span> 关于我</span></a></div><div class="menus_item"><a class="site-page" href="/blog/"><i class="fa-fw fas fa-home"></i><span> 主页</span></a></div><div class="menus_item"><a class="site-page" href="/blog/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/blog/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/blog/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header" style="background-image: url('/blog/img/hbs.png')"><nav id="nav"><span id="blog_name"><a id="site-name" href="/blog/">小黑博客</a></span><div id="menus"><div id="search-button"><a class="site-page social-icon search"><i class="fas fa-search fa-fw"></i><span> 搜索</span></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/blog/about/"><i class="fa-fw fas fa-heart"></i><span> 关于我</span></a></div><div class="menus_item"><a class="site-page" href="/blog/"><i class="fa-fw fas fa-home"></i><span> 主页</span></a></div><div class="menus_item"><a class="site-page" href="/blog/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/blog/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/blog/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div></div><div id="toggle-menu"><a class="site-page"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">54-Canvas</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2021-01-25T01:46:23.000Z" title="发表于 2021-01-25 09:46:23">2021-01-25</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2021-08-29T11:36:10.269Z" title="更新于 2021-08-29 19:36:10">2021-08-29</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/blog/categories/%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/">学习笔记</a><i class="fas fa-angle-right post-meta-separator"></i><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/blog/categories/%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/JavaScript%E9%AB%98%E7%BA%A7%E7%A8%8B%E5%BA%8F%E8%AE%BE%E8%AE%A1/">JavaScript高级程序设计</a><i class="fas fa-angle-right post-meta-separator"></i><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/blog/categories/%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/JavaScript%E9%AB%98%E7%BA%A7%E7%A8%8B%E5%BA%8F%E8%AE%BE%E8%AE%A1/%E7%AC%AC18%E7%AB%A0%E2%80%94%E2%80%94%E5%8A%A8%E7%94%BB%E4%B8%8ECanvas%E5%9B%BE%E5%BD%A2/">第18章——动画与Canvas图形</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-wordcount"><i class="far fa-file-word fa-fw post-meta-icon"></i><span class="post-meta-label">字数总计:</span><span class="word-count">1.6k</span><span class="post-meta-separator">|</span><i class="far fa-clock fa-fw post-meta-icon"></i><span class="post-meta-label">阅读时长:</span><span>6分钟</span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><h2 id="画布类型"><a href="#画布类型" class="headerlink" title="画布类型"></a>画布类型</h2><ul>
<li><code>2d</code></li>
<li><code>webgl</code></li>
</ul>
<h2 id="使用步骤"><a href="#使用步骤" class="headerlink" title="使用步骤"></a>使用步骤</h2><ul>
<li>获取 <code>element</code></li>
<li>获取上下文对象 <code>ctx = element.getContext(&#39;2d&#39; || &#39;webgl&#39;)</code></li>
<li>绘制</li>
<li>导出图片 <code>element.toDataURL(&#39;MIME/TYPE&#39;)</code></li>
</ul>
<h2 id="2d上下文"><a href="#2d上下文" class="headerlink" title="2d上下文"></a><code>2d</code>上下文</h2><ul>
<li>可绘制简单的<code>2d</code>图形，比如矩形、弧线和路径</li>
<li><code>ctx.save()</code> 保存现场</li>
<li><code>ctx.restore()</code> 恢复现场</li>
</ul>
<h3 id="画笔属性"><a href="#画笔属性" class="headerlink" title="画笔属性"></a>画笔属性</h3><table>
<thead>
<tr>
<th align="left"><code>name</code></th>
<th align="left"><code>des</code></th>
</tr>
</thead>
<tbody><tr>
<td align="left"><code>fillStyle</code></td>
<td align="left">设置或返回用于<strong>填充</strong>绘画的颜色、渐变或模式</td>
</tr>
<tr>
<td align="left"><code>strokeStyle</code></td>
<td align="left">设置或返回用于<strong>笔触</strong>的颜色、渐变或模式</td>
</tr>
<tr>
<td align="left"><code>shadowColor</code></td>
<td align="left">设置或返回用于<strong>阴影</strong>的颜色，默认黑色</td>
</tr>
<tr>
<td align="left"><code>shadowBlur</code></td>
<td align="left">设置或返回用于阴影的模糊级别，默认0</td>
</tr>
<tr>
<td align="left"><code>shadowOffsetX</code></td>
<td align="left">设置或返回阴影距形状的水平距离，默认0</td>
</tr>
<tr>
<td align="left"><code>shadowOffsetY</code></td>
<td align="left">设置或返回阴影距形状的垂直距离， 默认0</td>
</tr>
<tr>
<td align="left"><code>lineCap</code></td>
<td align="left">设置或返回线条的结束端点样式</td>
</tr>
<tr>
<td align="left"><code>lineJoin</code></td>
<td align="left">设置或返回两条线相交时，所创建的拐角类型</td>
</tr>
<tr>
<td align="left"><code>lineWidth</code></td>
<td align="left">设置或返回当前的线条宽度</td>
</tr>
<tr>
<td align="left"><code>miterLimit</code></td>
<td align="left">设置或返回最大斜接长度</td>
</tr>
</tbody></table>
<h3 id="矩形"><a href="#矩形" class="headerlink" title="矩形"></a>矩形</h3><ul>
<li><code>fillRect(x, y, width, height)</code> 填充矩形</li>
<li><code>strokeRect(x, y, width, height)</code> 矩形描边</li>
<li><code>clearRect(x, y, width, height)</code> 清除矩形区域</li>
</ul>
<h3 id="路径"><a href="#路径" class="headerlink" title="路径"></a>路径</h3><ul>
<li><code>beginPath()</code> 开始绘制新路径</li>
<li><code>closePath()</code> 绘制一条连接到起点的线条</li>
<li><code>fill()</code> 填充路径</li>
<li><code>stroke()</code> 给路径描边</li>
<li><code>clip()</code> 剪切路径所包含的区域，填充在外部的图像不会显示</li>
<li><code>isPointInPath(x, y)</code> 确定(x, y) 是否位于路径上</li>
</ul>
<table>
<thead>
<tr>
<th align="left"><code>method</code></th>
<th align="left"><code>des</code></th>
</tr>
</thead>
<tbody><tr>
<td align="left"><code>arc(x, y, r, start, end, isReverse)</code></td>
<td align="left">以<code>(x, y)</code>为圆心，<code>r</code>为半径，起始角<code>start</code>（弧度）,结束角<code>end</code>，是否逆时针绘制(<code>true</code>)</td>
</tr>
<tr>
<td align="left"><code>arcTo(x1, y1, x2, y2, r)</code></td>
<td align="left">从上一点开始绘制一条弧线，到<code>(x2, y2)</code> 为止，并以半径r穿过<code>(x1, y1)</code></td>
</tr>
<tr>
<td align="left"><code>quadraticCurveTo(c1x, c1y, x, y)</code></td>
<td align="left">从上一点开始绘制一条二次贝塞尔曲线，到<code>(x, y) </code>为止，以<code>(c1x, c1y)</code>为控制点</td>
</tr>
<tr>
<td align="left"><code>bezierCurveTo(c1x, c1y, c2x, c2y, x, y)</code></td>
<td align="left">从上一点开始绘制一条三次贝塞尔曲线，到<code>(x, y)</code> 为止，以<code>(c1x, c1y)</code>，<code>(c2x, c2y)</code>为控制点</td>
</tr>
<tr>
<td align="left"><code>lineTo(x, y)</code></td>
<td align="left">从上一点开始绘制一条直线到<code>(x, y)</code>为止</td>
</tr>
<tr>
<td align="left"><code>moveTo(x, y)</code></td>
<td align="left">将画笔移动到<code>(x, y)</code>不绘制图形</td>
</tr>
<tr>
<td align="left"><code>rect(x, y, width, height)</code></td>
<td align="left">从<code>(x, y)</code>开始绘制一个矩形路径</td>
</tr>
</tbody></table>
<h3 id="文本"><a href="#文本" class="headerlink" title="文本"></a>文本</h3><ul>
<li><code>fillText(str, x, y, maxwidth)</code> 绘制文本</li>
<li><code>strokeText(str, x, y, maxwidth)</code> 文本描边</li>
</ul>
<table>
<thead>
<tr>
<th align="left"><code>context</code>属性</th>
<th align="left"><code>des</code></th>
</tr>
</thead>
<tbody><tr>
<td align="left"><code>font</code></td>
<td align="left">字体，<code>&quot;10px Arial&quot;</code></td>
</tr>
<tr>
<td align="left"><code>textAlign</code></td>
<td align="left">对齐方式，<code>start,center,end</code></td>
</tr>
<tr>
<td align="left"><code>textBaseline</code></td>
<td align="left">文本的基线，<code>top,hanging,middle,alphabetic,ideographic,bottom</code></td>
</tr>
</tbody></table>
<h3 id="变换"><a href="#变换" class="headerlink" title="变换"></a>变换</h3><table>
<thead>
<tr>
<th align="left"><code>name</code></th>
<th align="left"><code>des</code></th>
</tr>
</thead>
<tbody><tr>
<td align="left"><code>rotate(angle)</code></td>
<td align="left">围绕原点旋转<code>angle</code>弧度</td>
</tr>
<tr>
<td align="left"><code>scale(x, y)</code></td>
<td align="left"><code>x</code>方向变换<code>x</code>倍，<code>y</code>方向变换<code>y</code>倍</td>
</tr>
<tr>
<td align="left"><code>translate(x, y)</code></td>
<td align="left">移动坐标原点到<code>(x, y)</code></td>
</tr>
<tr>
<td align="left"><code>transform()</code></td>
<td align="left">直接修改变换矩阵</td>
</tr>
<tr>
<td align="left"><code>setTransform()</code></td>
<td align="left">将变换矩阵重置为默认状态，再调用<code>transform()</code></td>
</tr>
</tbody></table>
<h3 id="图像"><a href="#图像" class="headerlink" title="图像"></a>图像</h3><ul>
<li><code>drawImage()</code></li>
<li>可绘制图像、画布或视频</li>
<li>不支持跨域</li>
</ul>
<table>
<thead>
<tr>
<th align="left"><code>use</code></th>
<th align="left"><code>des</code></th>
</tr>
</thead>
<tbody><tr>
<td align="left"><code>(img, x, y)</code></td>
<td align="left"><code>img</code>元素，绘制图像的起点，终点</td>
</tr>
<tr>
<td align="left"><code>(img, x, y, width, height)</code></td>
<td align="left"><code>img</code>元素，绘制图像的起点，终点，绘制后的宽度和高度（可用于缩放）</td>
</tr>
<tr>
<td align="left"><code>(img, sx, sy, sw, sh, dx, dy, dw, dh)</code></td>
<td align="left"><code>img</code>元素，原图中的起点，终点，宽度，高度，目标画布中的起点，终点，宽度，高度</td>
</tr>
</tbody></table>
<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&lt;!DOCTYPE <span class="meta-keyword">html</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">html</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">head</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">meta</span> <span class="attr">http-equiv</span>=<span class="string">&quot;Content-Type&quot;</span> <span class="attr">content</span>=<span class="string">&quot;text/html;charset=UTF-8&quot;</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">title</span>&gt;</span>Canvas测试<span class="tag">&lt;/<span class="name">title</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">head</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">body</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">p</span>&gt;</span>要使用的视频：<span class="tag">&lt;/<span class="name">p</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">video</span> <span class="attr">id</span>=<span class="string">&quot;video1&quot;</span> <span class="attr">controls</span> <span class="attr">width</span>=<span class="string">&quot;270&quot;</span> <span class="attr">src</span>=<span class="string">&quot;https://www.runoob.com/wp-content/uploads/2013/11/mov_bbb.mp4&quot;</span> <span class="attr">autoplay</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">video</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">p</span>&gt;</span>画布（每 20 毫秒，代码就会绘制视频的当前帧）：<span class="tag">&lt;/<span class="name">p</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">canvas</span> <span class="attr">id</span>=<span class="string">&quot;myCanvas&quot;</span> <span class="attr">width</span>=<span class="string">&quot;270&quot;</span> <span class="attr">height</span>=<span class="string">&quot;135&quot;</span> <span class="attr">style</span>=<span class="string">&quot;border:1px solid #d3d3d3;&quot;</span>&gt;</span></span><br><span class="line">        Your browser does not support the HTML5 canvas tag.</span><br><span class="line">    <span class="tag">&lt;/<span class="name">canvas</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">script</span>&gt;</span></span><br><span class="line"><span class="javascript">        <span class="keyword">const</span> v = <span class="built_in">document</span>.getElementById(<span class="string">&quot;video1&quot;</span>);</span></span><br><span class="line"><span class="javascript">        <span class="keyword">const</span> c = <span class="built_in">document</span>.getElementById(<span class="string">&quot;myCanvas&quot;</span>);</span></span><br><span class="line"><span class="javascript">        ctx = c.getContext(<span class="string">&#x27;2d&#x27;</span>);</span></span><br><span class="line"></span><br><span class="line"><span class="javascript">        <span class="keyword">let</span> i;</span></span><br><span class="line"><span class="javascript">        v.addEventListener(<span class="string">&#x27;play&#x27;</span>, <span class="function">() =&gt;</span> &#123;</span></span><br><span class="line"><span class="javascript">          i = <span class="built_in">window</span>.setInterval(<span class="function">() =&gt;</span> &#123;</span></span><br><span class="line">            ctx.drawImage(v, 0, 0, 270, 135)</span><br><span class="line">          &#125;, 20);</span><br><span class="line">        &#125;);</span><br><span class="line"><span class="javascript">        v.addEventListener(<span class="string">&#x27;pause&#x27;</span>, <span class="function">() =&gt;</span> &#123;</span></span><br><span class="line"><span class="javascript">          <span class="built_in">window</span>.clearInterval(i);</span></span><br><span class="line">        &#125;);</span><br><span class="line"><span class="javascript">        v.addEventListener(<span class="string">&#x27;ended&#x27;</span>, <span class="function">() =&gt;</span> &#123;</span></span><br><span class="line"><span class="javascript">          <span class="built_in">clearInterval</span>(i);</span></span><br><span class="line">        &#125;);</span><br><span class="line">    <span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">body</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">html</span>&gt;</span></span><br></pre></td></tr></table></figure>

<h3 id="渐变"><a href="#渐变" class="headerlink" title="渐变"></a>渐变</h3><h4 id="线性渐变"><a href="#线性渐变" class="headerlink" title="线性渐变"></a>线性渐变</h4><ul>
<li><code>createLinearGradient(sx, sy, ex, ey)</code> 创建渐变对象，起点x，起点y，终点x，终点y</li>
<li><code>addColorStop(0 ~ 1, colorstring)</code> 指定起点 ~ 终点颜色</li>
<li>将渐变对象赋给<code>fillStyle</code> 或 <code>strokeStyle</code></li>
</ul>
<h4 id="径向渐变"><a href="#径向渐变" class="headerlink" title="径向渐变"></a>径向渐变</h4><ul>
<li><code>createRadialGradient(sx, sy, sr, ex, ey, er)</code> 创建渐变对象，起点x，起点y，起点半径，终点x，终点y，终点半径</li>
<li>指定颜色</li>
<li>将渐变对象赋给<code>fillStyle</code> 或 <code>strokeStyle</code></li>
</ul>
<h3 id="模式"><a href="#模式" class="headerlink" title="模式"></a>模式</h3><ul>
<li>重复的图像</li>
<li>类似于<code>css</code>的<code>repeat</code></li>
<li><code>createPattern(img, &#39;repeat&#39;)</code></li>
<li>将模式对象赋给<code>fillStyle</code> 或 <code>strokeStyle</code></li>
</ul>
<h3 id="使用图像的数据"><a href="#使用图像的数据" class="headerlink" title="使用图像的数据"></a>使用图像的数据</h3><ul>
<li>可对图像进行处理</li>
</ul>
<h4 id="getImageData"><a href="#getImageData" class="headerlink" title="getImageData"></a><code>getImageData</code></h4><ul>
<li><code>getImageData(x, y, w, h)</code> 要获取数据的区域的<code>x，y</code>以及宽度，高度</li>
<li>返回的对象具有<code>width</code>，<code>height</code>以及<code>data</code>三个属性</li>
<li><code>data</code>为保存图像数据的数组，每4个相邻的元素分别保存<code>r,g,b,a</code></li>
<li>取值均为<code>[0, 255]</code></li>
<li>求平均值再赋值可二值化</li>
</ul>
<h4 id="putImageData"><a href="#putImageData" class="headerlink" title="putImageData"></a><code>putImageData</code></h4><ul>
<li><code>putImageData()</code></li>
</ul>
<table>
<thead>
<tr>
<th align="left">参数</th>
<th align="left">描述</th>
</tr>
</thead>
<tbody><tr>
<td align="left"><code>imgData</code></td>
<td align="left">规定要放回画布的 <code>ImageData</code> 对象</td>
</tr>
<tr>
<td align="left"><code>x</code></td>
<td align="left"><code>ImageData </code>对象左上角的 <code>x</code> 坐标，以像素计</td>
</tr>
<tr>
<td align="left"><code>y</code></td>
<td align="left"><code>ImageData </code>对象左上角的 <code>y</code> 坐标，以像素计</td>
</tr>
<tr>
<td align="left"><code>dirtyX</code></td>
<td align="left">可选。在画布上放置图像<code>x</code>的位置</td>
</tr>
<tr>
<td align="left"><code>dirtyY</code></td>
<td align="left">可选。在画布上放置图像<code>y</code>的位置</td>
</tr>
<tr>
<td align="left"><code>dirtyWidth</code></td>
<td align="left">可选。在画布上绘制图像所使用的宽度</td>
</tr>
<tr>
<td align="left"><code>dirtyHeight</code></td>
<td align="left">可选。在画布上绘制图像所使用的高度</td>
</tr>
</tbody></table>
<h4 id="createImageData"><a href="#createImageData" class="headerlink" title="createImageData"></a><code>createImageData</code></h4><ul>
<li>创建新的空白<code>ImageData</code>对象</li>
<li>默认像素值 <code>transparent``black</code></li>
<li><code>createImageData(width,height)</code></li>
<li><code>createImageData(imageData)</code>只复制宽高，不复制内容</li>
</ul>
<h3 id="合成"><a href="#合成" class="headerlink" title="合成"></a>合成</h3><ul>
<li><code>ctx.globalAlpha</code> 全局透明度</li>
<li><code>globalCompositionOperation</code> 后绘制的图形与先绘制的图形的位置关系</li>
</ul>
<table>
<thead>
<tr>
<th align="left"><code>value</code></th>
<th align="left"><code>des</code></th>
</tr>
</thead>
<tbody><tr>
<td align="left"><code>source-over</code></td>
<td align="left">后来居上，默认值</td>
</tr>
<tr>
<td align="left"><code>source-in</code></td>
<td align="left">重叠部分可见，两者其余部分全透明</td>
</tr>
<tr>
<td align="left"><code>source-out</code></td>
<td align="left">不重叠部分可见，先绘制的全透明</td>
</tr>
<tr>
<td align="left"><code>source-atop</code></td>
<td align="left">重叠部分可见，先绘制的不受影响</td>
</tr>
<tr>
<td align="left"><code>destination-over</code></td>
<td align="left">后绘制的位于下方，只有透明像素下的部分可见</td>
</tr>
<tr>
<td align="left"><code>destination-in</code></td>
<td align="left">后绘制的位于下方，两者其余部分全透明</td>
</tr>
<tr>
<td align="left"><code>destination-out</code></td>
<td align="left">后绘制的擦除重叠部分</td>
</tr>
<tr>
<td align="left"><code>destination-atop</code></td>
<td align="left">后绘制的位于下方，不重叠部分先绘制的变透明</td>
</tr>
<tr>
<td align="left"><code>lighter</code></td>
<td align="left">重叠部分的值相加，变亮</td>
</tr>
<tr>
<td align="left"><code>copy</code></td>
<td align="left">后绘制的图形完全替代与之重叠的先绘制的图形</td>
</tr>
<tr>
<td align="left"><code>xor</code></td>
<td align="left">重叠部分进行异或操作</td>
</tr>
</tbody></table>
</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="mailto:undefined">BluesYoung-web</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="https://bluesyoung-web.gitee.io/blog/2021-01-25-54-Canvas.html">https://bluesyoung-web.gitee.io/blog/2021-01-25-54-Canvas.html</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="https://BluesYoung-web.gitee.io/blog" target="_blank">小黑博客</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/blog/tags/JavaScript/">JavaScript</a><a class="post-meta__tags" href="/blog/tags/JavaScript%E9%AB%98%E7%BA%A7%E7%A8%8B%E5%BA%8F%E8%AE%BE%E8%AE%A1%E7%AC%AC%E5%9B%9B%E7%89%88/">JavaScript高级程序设计第四版</a></div><div class="post_share"></div></div><div class="post-reward"><div class="reward-button button--animated"><i class="fas fa-qrcode"></i> 打赏</div><div class="reward-main"><ul class="reward-all"><li class="reward-item"><a href="/blog/img/wx.png" target="_blank"><img class="post-qr-code-img" src="/blog/img/wx.png" alt="微信"/></a><div class="post-qr-code-desc">微信</div></li><li class="reward-item"><a href="/blog/img/zfb.jpg" target="_blank"><img class="post-qr-code-img" src="/blog/img/zfb.jpg" alt="支付宝"/></a><div class="post-qr-code-desc">支付宝</div></li></ul></div></div><div class="relatedPosts"><div class="headline"><i class="fas fa-thumbs-up fa-fw"></i><span> 相关推荐</span></div><div class="relatedPosts-list"><div><a href="/blog/2020-12-28-01-历史回顾.html" title="01-历史回顾"><img class="cover" src="/blog/img/hbs.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2020-12-28</div><div class="title">01-历史回顾</div></div></a></div><div><a href="/blog/2020-12-28-03-script元素.html" title="03-script元素"><img class="cover" src="/blog/img/hbs.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2020-12-28</div><div class="title">03-script元素</div></div></a></div><div><a href="/blog/2020-12-28-02-实现.html" title="02-实现"><img class="cover" src="/blog/img/hbs.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2020-12-28</div><div class="title">02-实现</div></div></a></div><div><a href="/blog/2020-12-28-04-文档模式.html" title="04-文档模式"><img class="cover" src="/blog/img/hbs.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2020-12-28</div><div class="title">04-文档模式</div></div></a></div><div><a href="/blog/2020-12-28-05-语法.html" title="05-语法"><img class="cover" src="/blog/img/hbs.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2020-12-28</div><div class="title">05-语法</div></div></a></div><div><a href="/blog/2020-12-28-06-变量声明.html" title="06-变量声明"><img class="cover" src="/blog/img/hbs.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2020-12-28</div><div class="title">06-变量声明</div></div></a></div></div></div></div><div class="aside-content" id="aside-content"><div class="card-widget card-info"><div class="is-center"><div class="avatar-img"><img src="/blog/img/lufei_siwangningshi.jpg" onerror="this.onerror=null;this.src='/blog/img/friend_404.gif'" alt="avatar"/></div><div class="author-info__name">BluesYoung-web</div><div class="author-info__description">一枚不善言辞的技术宅</div></div><div class="card-info-data is-center"><div class="card-info-data-item"><a href="/blog/archives/"><div class="headline">文章</div><div class="length-num">153</div></a></div><div class="card-info-data-item"><a href="/blog/tags/"><div class="headline">标签</div><div class="length-num">54</div></a></div><div class="card-info-data-item"><a href="/blog/categories/"><div class="headline">分类</div><div class="length-num">48</div></a></div></div><a class="button--animated" id="card-info-btn" target="_blank" rel="noopener" href="https://gitee.com/BluesYoung-web"><i class="fab fa-gitee"></i><span>点个小星星吧</span></a><div class="card-info-social-icons is-center"><a class="social-icon" href="https://github.com/BluesYoung-web" target="_blank" title="Github"><i class="fab fa-github"></i></a><a class="social-icon" href="mailto:15171255945@163.com" target="_blank" title="Email"><i class="fas fa-envelope"></i></a></div></div><div class="sticky_layout"><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item"><a class="thumbnail" href="/blog/2021-08-24-%E7%A7%BB%E5%8A%A8%E7%AB%AF%E8%BD%AF%E9%94%AE%E7%9B%98%E5%AF%BC%E8%87%B4%E5%B8%83%E5%B1%80%E9%94%99%E4%B9%B1.html" title="移动端软键盘导致布局错乱"><img src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/img/default.jpg" onerror="this.onerror=null;this.src='/blog/img/404.jpg'" alt="移动端软键盘导致布局错乱"/></a><div class="content"><a class="title" href="/blog/2021-08-24-%E7%A7%BB%E5%8A%A8%E7%AB%AF%E8%BD%AF%E9%94%AE%E7%9B%98%E5%AF%BC%E8%87%B4%E5%B8%83%E5%B1%80%E9%94%99%E4%B9%B1.html" title="移动端软键盘导致布局错乱">移动端软键盘导致布局错乱</a><time datetime="2021-08-24T10:01:20.000Z" title="发表于 2021-08-24 18:01:20">2021-08-24</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/blog/2021-08-16-Linux%E5%AE%89%E8%A3%85you-get.html" title="Linux安装you-get"><img src="/blog/img/shumeipai_cover.jpg" onerror="this.onerror=null;this.src='/blog/img/404.jpg'" alt="Linux安装you-get"/></a><div class="content"><a class="title" href="/blog/2021-08-16-Linux%E5%AE%89%E8%A3%85you-get.html" title="Linux安装you-get">Linux安装you-get</a><time datetime="2021-08-16T08:07:31.000Z" title="发表于 2021-08-16 16:07:31">2021-08-16</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/blog/2021-08-16-git%E5%88%A0%E9%99%A4%E8%BF%9C%E7%A8%8B%E4%BB%93%E5%BA%93%E7%9A%84%E6%8F%90%E4%BA%A4.html" title="git删除远程仓库的提交"><img src="/blog/img/skill.jpg" onerror="this.onerror=null;this.src='/blog/img/404.jpg'" alt="git删除远程仓库的提交"/></a><div class="content"><a class="title" href="/blog/2021-08-16-git%E5%88%A0%E9%99%A4%E8%BF%9C%E7%A8%8B%E4%BB%93%E5%BA%93%E7%9A%84%E6%8F%90%E4%BA%A4.html" title="git删除远程仓库的提交">git删除远程仓库的提交</a><time datetime="2021-08-16T07:52:02.000Z" title="发表于 2021-08-16 15:52:02">2021-08-16</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/blog/2021-08-13-%E5%B0%86pad%E6%89%A9%E5%B1%95%E4%B8%BA%E7%94%B5%E8%84%91%E7%9A%84%E5%89%AF%E5%B1%8F.html" title="将pad扩展为电脑的副屏"><img src="/blog/img/skill.jpg" onerror="this.onerror=null;this.src='/blog/img/404.jpg'" alt="将pad扩展为电脑的副屏"/></a><div class="content"><a class="title" href="/blog/2021-08-13-%E5%B0%86pad%E6%89%A9%E5%B1%95%E4%B8%BA%E7%94%B5%E8%84%91%E7%9A%84%E5%89%AF%E5%B1%8F.html" title="将pad扩展为电脑的副屏">将pad扩展为电脑的副屏</a><time datetime="2021-08-13T11:44:04.000Z" title="发表于 2021-08-13 19:44:04">2021-08-13</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/blog/2021-08-11-Linux%E5%90%AF%E7%94%A8SSH%E6%9C%8D%E5%8A%A1.html" title="Linux启用SSH服务"><img src="/blog/img/shumeipai_cover.jpg" onerror="this.onerror=null;this.src='/blog/img/404.jpg'" alt="Linux启用SSH服务"/></a><div class="content"><a class="title" href="/blog/2021-08-11-Linux%E5%90%AF%E7%94%A8SSH%E6%9C%8D%E5%8A%A1.html" title="Linux启用SSH服务">Linux启用SSH服务</a><time datetime="2021-08-11T10:50:04.000Z" title="发表于 2021-08-11 18:50:04">2021-08-11</time></div></div></div></div></div></div></main><footer id="footer"><div id="footer-wrap"><div class="copyright">&copy;2020 - 2021 By BluesYoung-web</div><div class="framework-info"><span>框架 </span><a target="_blank" rel="noopener" href="https://hexo.io">Hexo</a><span class="footer-separator">|</span><span>主题 </span><a target="_blank" rel="noopener" href="https://github.com/jerryc127/hexo-theme-butterfly">Butterfly</a></div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button id="go-up" type="button" title="回到顶部"><i class="fas fa-arrow-up"></i></button></div></div><div id="local-search"><div class="search-dialog"><div class="search-dialog__title" id="local-search-title">本地搜索</div><div id="local-input-panel"><div id="local-search-input"><div class="local-search-box"><input class="local-search-box--input" placeholder="搜索文章" type="text"/></div></div></div><hr/><div id="local-search-results"></div><span class="search-close-button"><i class="fas fa-times"></i></span></div><div id="search-mask"></div></div><div><script src="/blog/js/utils.js"></script><script src="/blog/js/main.js"></script><script src="https://cdn.jsdelivr.net/npm/node-snackbar/dist/snackbar.min.js"></script><script src="/blog/js/search/local-search.js"></script><script>var preloader = {
  endLoading: () => {
    document.body.style.overflow = 'auto';
    document.getElementById('loading-box').classList.add("loaded")
  },
  initLoading: () => {
    document.body.style.overflow = '';
    document.getElementById('loading-box').classList.remove("loaded")

  }
}
window.addEventListener('load',preloader.endLoading())</script><div class="js-pjax"><script>if (document.getElementsByClassName('mermaid').length) {
  if (window.mermaidJsLoad) mermaid.init()
  else {
    getScript('https://cdn.jsdelivr.net/npm/mermaid/dist/mermaid.min.js').then(() => {
      window.mermaidJsLoad = true
      mermaid.initialize({
        theme: 'default',
      })
      false && mermaid.init()
    })
  }
}</script></div><script src="https://cdn.jsdelivr.net/npm/jquery@latest/dist/jquery.min.js"></script> <script src="/blog/js/xkTool.js"></script> <script src="/blog/js/mySelf.js"></script><canvas class="fireworks" mobile="false"></canvas><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/dist/fireworks.min.js"></script><script id="canvas_nest" defer="defer" color="0,0,255" opacity="0.7" zIndex="-1" count="99" mobile="false" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/dist/canvas-nest.min.js"></script></div></body></html>